//
//  BN_ForgetPasswordView.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-5-25.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "BN_ForgetPasswordView.h"
#import "BN_MyInfoHelper.h"

@implementation BN_ForgetPasswordView {
    BN_MyInfoHelper *myInfoHelper_;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)awakeFromNib {
    UIColor *color = APP_OBJECT_GREEN_COLOR;
    self.navView.backgroundColor = color;
    self.titleLabel.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:18];
    self.youXiangTextfield.returnKeyType = UIReturnKeySend;
    self.youXiangTextfield.delegate = self;
    self.youXiangTextfield.keyboardType = UIKeyboardTypeEmailAddress;
    [self.youXiangTextfield becomeFirstResponder];
    [self.backViewBtn addTarget:self action:@selector(backviewAction) forControlEvents:UIControlEventTouchUpInside];
    
    // 交互
    [self.saveInfoBtn addTarget:self action:@selector(toSaveAction) forControlEvents:UIControlEventTouchUpInside];
    
    // helper
    myInfoHelper_ = [[BN_MyInfoHelper alloc]init];
    
}

#pragma mark TextField Delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self toSaveAction];
    return YES;
}

#pragma mark
#pragma mark Action
- (void)backviewAction {
    [self removeFromSuperview];
}

- (void)toSaveAction {
    [self.youXiangTextfield resignFirstResponder];
    BOOL isLawful = [self isValidateEmail:self.youXiangTextfield.text];
    if (isLawful) {
        [SVProgressHUD showWithStatus:@"保存中..." maskType:SVProgressHUDMaskTypeBlack];
        NSString *mail = self.youXiangTextfield.text;
        __weak typeof(self) weakSelf = self;
        [myInfoHelper_ updateUserInfoWithMail:mail completeHandler:^(id result, NSString *errMsg) {
            if (errMsg) {
                [SVProgressHUD dismiss];
                [LZCHINT title:errMsg type:LZCSuccess duration:3 places:HINT_PLACES callBack:NULL];
            }else{
                [SVProgressHUD dismiss];
                weakSelf.youXiangTextfield.delegate = nil;
                [LZCHINT title:@"密码已发送到您的邮箱请注意查收" type:LZCSuccess duration:3 places:HINT_PLACES callBack:NULL];
                [weakSelf performSelector:@selector(removeView) withObject:nil afterDelay:2];
            }
        }];
    }else {
        [LZCHINT title:@"请填写正确的邮箱地址" type:LZCSuccess duration:3 places:HINT_PLACES callBack:NULL];
    }

}

- (void)removeView {
    [self removeFromSuperview];
}

- (BOOL)isValidateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex];
    return [emailTest evaluateWithObject:email];
}

@end
